/*
 * Copyright 2010-2012 Alfresco Software Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file is part of an unsupported extension to Alfresco.
 *
 * File Description:
 * This file contains the JavaScript used to obtain the activity stream
 * to display in the pop-up window each time the user clicks the toolbar
 * button.
 */ 

// In order to prevent XSS attacks the manifest.json file will have been explicitly set
// with the domain that can be accessed (the domain can be modified in the build.properties
// file). This domain should also be used to set the explit URLs for accessing content.
var @ID_PREFIX@domain = "@HTTP_DOMAIN@"; // This should NOT say HTTP_DOMAIN - it should be replaced by the build process

var @ID_PREFIX@firstTime = true;
var @ID_PREFIX@requestFailureCount = 0;  // used for exponential backoff
var @ID_PREFIX@requestTimeout = 1000 * 2;  // 5 seconds
var @ID_PREFIX@requestTimerId;
var @ID_PREFIX@loggedOut = false;

function @ID_PREFIX@setContent(content)
{
    var activitiesContainer = document.getElementById("@ID_PREFIX@activities");
	
	Application.console.log("Target Element: " + activitiesContainer.id);
    while (activitiesContainer.hasChildNodes()) 
	{
        activitiesContainer.removeChild(activitiesContainer.lastChild);
    }

	Application.console.log("Cleared old children");
	
    // This is needed to make sure that we pick up the correct CSS for the XHR response...	
	var prefix = "<div class=\"sticky-wrapper sticky-footer activities alfreso-activities-panel\">";
	var suffix = "</div>";
	
	// Parse the fragment - this guarantees security against malicious HTML and man-in-the-middle
	// attacks... plus, it's really the only way to do this.
	var fragment = Components.classes["@mozilla.org/feed-unescapehtml;1"]  
                             .getService(Components.interfaces.nsIScriptableUnescapeHTML)  
                             .parseFragment(prefix + content + suffix, false, null, activitiesContainer);  
    activitiesContainer.appendChild(fragment);  
	Application.console.log("Content set");
}

function @ID_PREFIX@getActivities() 
{
    Application.console.log("Getting activities");
    // Clear any previously displayed notifications generated by the background thread
	// and reset the previous stored acknowledgement data...
    if (@ID_PREFIX@worker.lastNotification) 
	{
		@ID_PREFIX@worker.lastNotification.cancel();
	}
    window.content.localStorage.@ID_PREFIX@lastAcknowledgedPost = window.content.localStorage.@ID_PREFIX@latestPost;
    window.content.localStorage.@ID_PREFIX@lastNotificationSize = -1;
	if (@ID_PREFIX@worker.badge)
	{
		@ID_PREFIX@worker.badge.setAttribute("value", 0);
	}
	// Pop up a loading prompt...
    @ID_PREFIX@setContent("<span>Loading...</span>");
	
	Application.console.log("3");
	function onSuccess(html) 
	{
        @ID_PREFIX@worker.button.classList.remove("@ID_PREFIX@disabled-button");  
        @ID_PREFIX@worker.button.classList.add("@ID_PREFIX@button");
        var replaceString = "\"" + @ID_PREFIX@domain + "share/";
        html = html.replace(/"\/share\//g, replaceString);
		@ID_PREFIX@setContent(html);
	}
	function onError(error)
	{
		// Need to show some kind of failed icon
		@ID_PREFIX@setContent("<html:span>Unable to load activities - please ensure that you are <html:a href='" + @ID_PREFIX@domain + "share'>signed in</html:a> to Alfresco Share</html:span>");
		Application.console.log("An error occurred getting the activities"); 
        @ID_PREFIX@worker.badge.setAttribute("value", "X");     
        @ID_PREFIX@worker.button.classList.remove("@ID_PREFIX@button");
        @ID_PREFIX@worker.button.classList.add("@ID_PREFIX@disabled-button");        
	}
    @ID_PREFIX@makeXhr(@ID_PREFIX@domain + "share/service/components/dashlets/activities/list?site=&mode=user&dateFilter=28&userFilter=others&activityFilter=", onSuccess, onError);
	return true;
}
  
function @ID_PREFIX@makeXhr(url, onSuccess, onError)
{
    var xhr = new XMLHttpRequest();
    var abortTimerId = window.setTimeout(function() 
    { 
        xhr.abort();  // synchronously calls onreadystatechange
    }, @ID_PREFIX@requestTimeout);

    function handleSuccess(count) 
    {
        @ID_PREFIX@requestFailureCount = 0;
        window.clearTimeout(abortTimerId);
        if (onSuccess)
        {
            onSuccess(count);
	    }
    }

    var invokedErrorCallback = false;
    function handleError(error) 
    {
        ++@ID_PREFIX@requestFailureCount;
        window.clearTimeout(abortTimerId);
        if (onError && !invokedErrorCallback)
	    {
            onError(error);
	    }
        invokedErrorCallback = true;
    }

    try 
	{
	    // Handle changes in the response...
        xhr.onreadystatechange = function()
	    {
		    // Still waiting for the response to complete...
            if (xhr.readyState != 4)
	        { 
                return;
            }
			else if (xhr.status == 401 || xhr.status == 403)
			{
				// The user is not authenticated. Disable polling.
				@ID_PREFIX@loggedOut = true;
                handleError();
			}
			else if (xhr.status == 200)
			{
				@ID_PREFIX@loggedOut = false;
                if (xhr.responseText) 
                {
                    handleSuccess(xhr.responseText);
                    return;
                }
			}
            else if (xhr.status == 0)
            {
                window.setTimeout(function() {
                    @ID_PREFIX@makeXhr(url, onSuccess, onError)
                }, 1000);
            }
            else
            {
                handleError();
            }            
        }

		// Override the default error handling function to call the one passed as
		// an argument...
        xhr.onerror = function(error) 
	    {
            handleError(error);
        }

		// Make the request...
        xhr.open("GET", url, true);  // TODO: Need to set correct authentication...
        xhr.send(null);
    } 
    catch(e) 
    {
        Application.console.log("Failed to load activities" + e);
        handleError();
    }
}

$('div.alfreso-ts-activities-panel a').live('click', function(e) {
  e.preventDefault();
  var href = e.currentTarget.href;
  var tBrowser = top.document.getElementById("content");
  var tab = tBrowser.addTab(e.currentTarget.href);
  tBrowser.selectedTab = tab;
  document.getElementById("@ID_PREFIX@activities").hidePopup();
});
